<template>
  <div class="container">
    <h2 class="page-title">个人信息修改</h2>
    <form class="profile-card" @submit.prevent="submitForm">
      <!-- 用户名称 -->
      <div class="form-group" @mouseenter="hoverField = 'userName'" @mouseleave="hoverField = null">
        <label class="form-label">用户名称</label>
        <template v-if="!editing.userName">
          <div class="form-value">{{ formData.userName }}</div>
          <button v-show="hoverField === 'userName'" class="edit-btn" @click.stop="startEditing('userName', $event)">编辑</button>
        </template>
        <input v-else type="text" class="form-control" v-model="tempData.userName" 
              ref="userNameInput" @keydown.enter="saveEditing('userName')" @blur="saveEditing('userName')">
      </div>
      
      <!-- 出生日期 -->
      <div class="form-group" @mouseenter="hoverField = 'userBirthday'" @mouseleave="hoverField = null">
        <label class="form-label">出生日期</label>
        <template v-if="!editing.userBirthday">
          <div class="form-value">{{ formData.userBirthday }}</div>
          <button v-show="hoverField === 'userBirthday'" class="edit-btn" @click.stop="startEditing('userBirthday', $event)">编辑</button>
        </template>
        <el-date-picker
          v-else
          v-model="tempData.userBirthday"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          ref="birthdayPicker"
          @change="saveEditing('userBirthday')"
          @blur="saveEditing('userBirthday')">
        </el-date-picker>
      </div>
      
      <!-- 用户地址 -->
      <div class="form-group" @mouseenter="hoverField = 'userLocation'" @mouseleave="hoverField = null">
        <label class="form-label">用户地址</label>
        <template v-if="!editing.userLocation">
          <div class="form-value">{{ formData.userLocation }}</div>
          <button v-show="hoverField === 'userLocation'" class="edit-btn" @click.stop="startEditing('userLocation', $event)">编辑</button>
        </template>
        <input v-else type="text" class="form-control" v-model="tempData.userLocation" 
              ref="locationInput" @keydown.enter="saveEditing('userLocation')" @blur="saveEditing('userLocation')">
      </div>
      
      <!-- 个人简介 -->
      <div class="form-group" @mouseenter="hoverField = 'userProfile'" @mouseleave="hoverField = null">
        <label class="form-label">个人简介</label>
        <template v-if="!editing.userProfile">
          <div class="form-value" style="white-space: pre-line;">{{ formData.userProfile }}</div>
          <button v-show="hoverField === 'userProfile'" class="edit-btn" @click.stop="startEditing('userProfile', $event)">编辑</button>
        </template>
        <textarea v-else class="form-control" v-model="tempData.userProfile" 
                ref="profileInput" @keydown.enter.ctrl="saveEditing('userProfile')" @blur="saveEditing('userProfile')"></textarea>
      </div>
      
      <div class="btn-container">
        <button type="submit" class="btn">保存修改</button>
      </div>
      <UserProfilePicture />
    </form>
  </div>
</template>

<script>
import UserProfilePicture from './UserProfilePicture.vue';

export default {
  name: "UserModifyInfo",
  components: {UserProfilePicture},
  data() {
    return {
      formData: {
        userName: "",
        userBirthday: "",
        userProfile: "",
        userLocation: "",
        userOldName: "",
        userAccount: ""
      },
      tempData: {
        userName: "",
        userBirthday: "",
        userProfile: "",
        userLocation: ""
      },
      editing: {
        userName: false,
        userBirthday: false,
        userProfile: false,
        userLocation: false,
      },
      hoverField: null
    }
  },
  methods: {
    startEditing(field, event) {
      event.stopPropagation();
      this.tempData = { ...this.formData };
      this.editing[field] = true;
      
      this.$nextTick(() => {
        const refName = field + 'Input';
        const input = this.$refs[refName];
        if (input) input.focus();
        
        if (field === 'userBirthday') {
          const picker = this.$refs.birthdayPicker;
          if (picker?.$el) {
            const dateInput = picker.$el.querySelector('input');
            if (dateInput) dateInput.focus();
          }
        }
      });
    },
    
    saveEditing(field) {
      this.$set(this.formData, field, this.tempData[field]);
      this.editing[field] = false;
    },
    
    cancelEditing(event) {
      const form = this.$el.querySelector('.profile-card');
      if (form && event && !form.contains(event.target)) {
        Object.keys(this.editing).forEach(key => {
          this.editing[key] = false;
        });
      }
    },
    
    submitForm() {
      Object.keys(this.editing).forEach(key => {
        if (this.editing[key]) {
          this.saveEditing(key);
        }
      });

      this.formData.userAccount = this.$store.state.user.userAccount
      this.$api.serviceUser.post('api/user/modifyUserInfo', this.formData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          this.$centerMessage({
            message: '修改用户基本信息成功',
            type: 'success'
          });
          this.$store.dispatch('user/login', response.data)
        }
        if (response.data.code == 40910){
          this.$centerMessage({
            message: response.data.message,
            type: 'error'
          });
        }
      })
      .catch(error => {
        console.log('失败', error);
      });
    },

    getUserInfoData() {
      this.$api.serviceUser.post('api/user/queryUserInfo', {'userAccount': this.$store.state.user.userAccount}, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          this.formData = response.data.data;
          console.log(this.formData);
          this.tempData = { ...response.data.data };
          console.log(this.formData);
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
  },
  mounted() {
    this.getUserInfoData();
    document.addEventListener('click', (event) => {
      this.cancelEditing(event);
    });
  },
  beforeDestroy() {
    document.removeEventListener('click', this.cancelEditing);
  }
}
</script>

<style scoped>
/* 保持原有样式完全不变 */
.container {
  width: 400px;
  margin-left: 50px;
}

.page-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 22px;
  font-weight: 500;
}

.profile-card {
  border-radius: 4px;
  position: relative;
}

.form-group {
  margin-bottom: 15px;
  position: relative;
  padding: 8px 0;
  min-height: 60px;
}

.form-label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #666;
  font-size: 13px;
}

.form-value {
  font-size: 15px;
  padding: 6px 0;
  min-height: 24px;
  width: calc(100% - 50px);
  word-break: break-word;
}

.form-control {
  width: 94.5%;
  padding: 8px 10px;
  border: 1px solid #e8e8e8;
  border-radius: 3px;
  font-size: 14px;
  height: 35px;
  outline: none;
  background-color: #f8f8f8;
}

textarea.form-control {
  height: 100px;
  resize: none;
  padding: 8px 10px;
  overflow-y: auto;
}

.edit-btn {
  position: absolute;
  right: 0;
  top: 28px;
  background-color: white;
  border: 0px solid #d9d9d9;
  border-radius: 2px;
  padding: 2px 8px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  display: none;
}

.form-group:hover .edit-btn {
  display: block;
}

.btn {
  display: inline-block;
  padding: 8px 20px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 3px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin: 0 auto;
}

.btn:hover {
  background-color: #d9363e;
}

.btn-container {
  text-align: center;
  margin-top: 20px;
}

.el-date-editor.el-input {
  width: 100% !important;
}
.el-input__inner {
  height: 35px !important;
  line-height: 35px !important;
  border-color: #e8e8e8 !important;
}
</style>